package com.twohand.admin.Util;

import com.tencent.cloud.CosStsClient;
import com.tencent.cloud.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.TreeMap;

@Component
public class CosUpload {
    @Value("${custom.SecretId}")
    public String SecretId;
    @Value("${custom.SecretKey}")
    public String SecretKey;

    @Value("${custom.cosDuration}")
    public Integer cosDuration;

    public Response getTempCred(String bucketName,String bucketOrigin) throws IOException {
        TreeMap<String,Object> config = new TreeMap<String,Object>();
        // 云 api 密钥 SecretId
        config.put("secretId", SecretId);
        // 云 api 密钥 SecretKey
        config.put("secretKey", SecretKey);

        // 临时密钥有效时长，单位是秒
        config.put("durationSeconds", cosDuration);

        // 换成你的 bucket
        config.put("bucket", bucketName);
        // 换成 bucket 所在地区
        config.put("region", bucketOrigin);

        // System.out.println("ceshi"+bucketName+"---"+bucketOrigin);
        // 可以通过 allowPrefixes 指定前缀数组, 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        config.put("allowPrefixes", new String[] {
                "*",
        });

        // 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        String[] allowActions = new String[] {
                // 简单上传
                "name/cos:PutObject",
                "name/cos:PostObject",
                // 分片上传
                "name/cos:InitiateMultipartUpload",
                "name/cos:ListMultipartUploads",
                "name/cos:ListParts",
                "name/cos:UploadPart",
                "name/cos:CompleteMultipartUpload"
        };
        config.put("allowActions", allowActions);
        Response response = CosStsClient.getCredential(config);
        // System.out.println(response.credentials.tmpSecretId);
        // System.out.println(response.credentials.tmpSecretKey);
        // System.out.println(response.credentials.sessionToken);
        return response;
    }
}
